<template>
  <div>
    <el-card class="box-card">
      <!-- 头部 -->
      <div slot="header">
        <span>账号列表</span>
        <!-- 内容 -->
        <div class="content">
          <!-- 表格 -->
          <el-table
            :data="tableData"
            :style="{ width: w + 'px' }"
            ref="accoutTable"
            @selection-change="handleSelectChange"
          >
            <!-- 选择框 -->
            <el-table-column type="selection" width="55"> </el-table-column>
            <!-- 账号 -->

            <el-table-column prop="account" label="账号"> </el-table-column>
            <!-- 用户组 -->
            <el-table-column prop="userGroup" label="用户组"> </el-table-column>
            <!-- 创建时间 -->
            <!-- <el-table-column prop="ctime" label="创建时间"> </el-table-column> -->
            <el-table-column label="创建时间">
              <template slot-scope="scope">
                <span>{{ scope.row.ctime | filterDate }}</span>
              </template>
            </el-table-column>
            <!-- 操作 -->
            <el-table-column label="操作" width="180">
              <template slot-scope="scope">
                <!-- 编辑按钮 -->
                <el-button size="mini" @click="handleEdit(scope.row)"
                  >编辑</el-button
                >

                <!-- 删除按钮 -->
                <el-popconfirm
                  @confirm="handleDelete(scope.row)"
                  @cancel="handleCancle"
                  confirm-button-text="确定"
                  cancel-button-text="取消"
                  icon="el-icon-info"
                  icon-color="red"
                  title="账户删除不能恢复，是否确定删除？"
                >
                  <el-button slot="reference" size="mini" type="danger"
                    >删除</el-button
                  >
                </el-popconfirm>
              </template>
            </el-table-column>
          </el-table>

          <!-- 分页 -->

          <el-pagination
            background
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="currentPage"
            :page-sizes="[3, 5, 10, 20, 30, 40]"
            :page-size="pageSize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
          >
          </el-pagination>

          <!-- 批量删除& 取消选择-->
          <el-button type="danger" size="small" @click="handleBatchDel"
            >批量删除</el-button
          >
          <el-button type="primary" size="small" @click="cancelSelect"
            >取消选择</el-button
          >
        </div>
      </div>
    </el-card>
    <!-- 弹出框 编辑 -->
    <el-dialog title="编辑账号" :visible.sync="dialogVisible" width="400px">
      <!-- 表格 -->
      <el-form label-width="80px" size="small" :model="editForm" :rules="rules">
        <!-- 账号 -->
        <el-form-item label="账号" prop="account">
          <el-input class="account" v-model="editForm.account"></el-input>
        </el-form-item>

        <!-- 用户组 -->
        <el-form-item label="用户组" prop="userGroup">
          <el-select v-model="editForm.userGroup">
            <el-option value="超级管理员">超级管理员</el-option>
            <el-option value="普通管理员">普通管理员</el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button size="small" @click="dialogVisible = false">取 消</el-button>
        <el-button size="small" type="primary" @click="saveEdit"
          >确 定</el-button
        >
      </span>
    </el-dialog>
  </div>
</template>

<script>
//引入工具函数  时间格式 批量删除
import { formaDate } from "../../utils/verification";
//引入ajax函数
import {
  getAccount,
  delAccount,
  aditAccount,
  batchDelAccount,
} from "../../api/user";
// console.log(getAccount,'11');

//引入弹出框的账号验证
import { checkName } from "../../utils/verification";
export default {
  //数据
  data() {
    return {
      tableData: [],
      // {
      //   id: 1,
      //   account: "刘大伟",
      //   userGroup: "超级管理员",
      //   ctime: "2022-06-26",
      // },
      // { id: 2, account: "赵四", userGroup: "普通管理员", ctime: "2022-06-26" },
      // { id: 3, account: "黄花", userGroup: "超级管理员", ctime: "2022-06-26" },
      // { id: 4, account: "翠芳", userGroup: "普通管理员", ctime: "2022-06-26" },
      // { id: 5, account: "狗哥", userGroup: "超级管理员", ctime: "2022-06-26" },
      // { id: 6, account: "哈哈", userGroup: "超级管理员", ctime: "2022-06-26" },

      //表格样式
      w: document.body.clientWidth - 200 - 40 - 40 - 20,

      currentPage: 1, //当前页
      pageSize: 5, //每页条数 每页3条数据
      total: 0, //数据总条数
      dialogVisible: false, //弹出框是隐藏还是显示

      //编辑表单双向绑定
      editForm: {
        account: "",
        userGroup: "",
      },
      //弹出框的表单验证
      //验证规则
      rules: {
        //账户
        account: [{ required: true, validator: checkName, trigger: "blur" }],
        //用户
        userGroup: [
          { required: true, message: "请选择用户组", trigger: "change" },
        ],
      },
      ids: [],
    };
  },
  //方法
  methods: {
    //获取数据
    async getData() {
      //发送ajax获取数据
      let res = await getAccount({
        currentPage: this.currentPage, //当前页码 第一页
        pageSize: this.pageSize, //每页条数 每页3条数据
      });
      console.log("22", res.data);

      //解构数据
      let { total, data } = res.data;
      // console.log(total, data, "333");
      //处理时间格式(在渲染前先处理格式)
      console.log(data, "44");
      data.map((v) => {
        formaDate(v.ctime);
        // console.log(formaDate(v.ctime), "kk");
        v.ctime = formaDate(v.ctime);
      });
      //赋值渲染
      this.total = total;
      this.tableData = data;

      //判断 如果当前页没有数据了
      if(!data.length||this.currentPage!==1){
        this.currentPage-=-1
        this.getData()//页面数据没有改，等同于刷新
      }
    },

    //编辑回填
    handleEdit(row) {
      //显示编辑弹框
      this.dialogVisible = true;
      //解构处理需要的参数
      let { id, account, userGroup } = row;
      //回填数据
      this.editForm = { id, account, userGroup };
      // console.log(row);
    },
    //保存编辑的结果
    async saveEdit() {
      let res = await aditAccount(this.editForm);
      this.dialogVisible = false; //关闭编辑的弹框
      let { code, msg } = res.data;
      if (code === 0) {
        // this.$message({
        //   message: msg,
        //   type: "success",
        // });
        this.getData(); //重新拉一下数据
      } else {
        // this.$message.error(msg);
      }
      // console.log(99);
    },
    //删除
    async handleDelete(row) {
      console.log(row, "row");
      let res = await delAccount({ id: row.id });
      console.log(res.data);
      //解构出数据
      let { code, msg } = res.data;
      //判断
      if (code === 0) {
        // this.$message({
        //   type: "success",
        //   message: msg,
        // });
        this.getData(); //再次请求数据：等价于刷新
      } else {
        // this.message.error(msg);
      }
    },
    //取消删除
    handleCancle() {
      this.$message("已取消");
    },
    //取消选择
    cancelSelect() {
      this.$refs.accoutTable.clearSelection();
    },
    //选项状态发送改变
    handleSelectChange(rows) {
      //把选中的数据id放入一个数组中
      this.ids = rows.map((v) => v.id);
      console.log(rows, "hh");
    },
    //批量删除
    handleBatchDel() {
      //排除没有选择直接点批量删除按钮
      if (!this.ids || !this.ids.length) {
        this.$message.error("至少请选择一项");
        return false;
      } else {
        //优化体验

        this.$confirm("此操作将永久删除, 是否继续?", "温馨提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        })
          .then(async () => {
            console.log({ ids: this.ids }, "hhhhhhhhhhh");
            let res = await batchDelAccount({ ids: this.ids });
            //解构
            let { code, msg } = res.data;
            console.log(code, msg, "zhu");
            if (code === 0) {
              // this.$message({
              //   type: "success",
              //   message: msg,
              // });
            }
            this.getData(); //重新拉一下数据
          })
          .catch(() => {
            this.$message({
              type: "info",
              message: "已取消删除",
            });
          });
      }
    },
    //窗口大小变化函数
    resize() {
      console.log(66);
      this.w = document.body.clientWidth - 200 - 40 - 40 - 20;
    },
    //每页条数改变
    handleSizeChange(val) {
      this.pageSize = val;
      this.getData();
      console.log(val);
    },

    //当前页改变就会触发
    handleCurrentChange(val) {
      this.currentPage = val;
      this.getData();
      console.log(val);
    },
  },
  //过滤器  date指的是scope.row.ctime 传入过滤器 调用工具函数的操作 将其变成合适的时间格式
  filters: {
    filterDate(date) {
      // console.log(date, "555");
      return formaDate(date);
    },
  },

  //生命周期（进来就要走）
  created() {
    //监听窗口大小变化
    window.addEventListener("resize", this.resize);

    //进入页面调用方法获取数据
    this.getData();
  },

  //销毁监听事件
  beforeDestory() {
    //组件销毁前 移出监听
    window.removeEventListener("resize", this.resize);
  },
};
</script>

<style lang="less" scoped>
/* 删除按钮 */
.el-button--danger {
  margin-left: 10px;
}
.el-pagination {
  margin-top: 18px;
  margin-bottom: 18px;
}
/* 修改的账号名的输入框 */
.account {
  width: 197px;
}
</style>